package com.northchurchcolumbus.podcast.ncpodcaster;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Map;

public class LameEncoder implements MP3Encoder
{

    public void encode(File input, File output, Map<String, String >ctx) throws Exception
    {
        Process lameProc = new ProcessBuilder(ctx.get("lame_path"), "-v", "--nohist", "-V9",
                        "--scale", "13", "-S", input.getAbsolutePath(),
                        output.getAbsolutePath()).start();

        InputStream s = new BufferedInputStream(lameProc.getErrorStream());
        byte[] bytes = new byte[1024];
        int bread = -1;
        while((bread=s.read(bytes))>=0)
        {
            String str = new String(bytes, 0, bread);
            System.out.print(str);
        }

        
        if ( lameProc.waitFor() > 0 )
        {
            s = lameProc.getErrorStream();
            bytes = new byte[1024];
            bread = -1;
            while((bread=s.read(bytes))>=0)
            {
                String str = new String(bytes, 0, bread);
                System.err.print(str);
            }
            throw new Exception("Error: " + lameProc.exitValue());
        }
        else
        {
            System.out.println("Exited properly");
        }
    }

}
